package com.sina.interfaces.test.util;

import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.springframework.test.web.servlet.ResultMatcher;

import java.time.format.DateTimeFormatter;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;

/**
 * 提供有些有用的方法 对测试结果的 json 进行验证.
 * 使用 org.hamcrest 和 JsonPath 对结果进行匹配
 * created  on 06/09/2017.
 */
public abstract class JsonMatcherUtils {


    private JsonMatcherUtils() {

    }

    public static ResultMatcher allMatchNotNull(String jsonpath) {
        return jsonPath( jsonpath ).value(
                CoreMatchers.allOf(
                        CoreMatchers.not( Matchers.emptyIterable() )
                        , CoreMatchers.everyItem( CoreMatchers.notNullValue() )
                )


        );
    }

    public static ResultMatcher allMatchIsAOrNull(String jsonpath, Class<?> clazz) {
        return jsonPath( jsonpath ).value(
                CoreMatchers.allOf(
                        CoreMatchers.not( Matchers.emptyIterable() ),
                        CoreMatchers.everyItem(
                                CoreMatchers.anyOf( CoreMatchers.isA( clazz ), CoreMatchers.nullValue() )

                        )
                )

        );
    }


    public static ResultMatcher allMatchNotNull(String jsonPath, Class<?> clazz) {
        return jsonPath( jsonPath ).value(
                CoreMatchers.allOf(
                        CoreMatchers.not( Matchers.emptyIterable() ),
                        CoreMatchers.everyItem(
                                CoreMatchers.allOf(
                                        Matchers.notNullValue(), CoreMatchers.isA( clazz )
                                )
                        )
                )

        );
    }

    public static ResultMatcher allMatchDateTime(String jsonPath, DateTimeFormatter formatter) {
        return jsonPath( jsonPath ).value(
                CoreMatchers.allOf(
                        CoreMatchers.not( Matchers.emptyIterable() ),
                        CoreMatchers.everyItem(
                                CoreMatchers.allOf(
                                        Matchers.notNullValue()
                                )
                        )
                )
        );
    }

}
